//
//  FCRegisteVC.m
//  FundChain
//
//  Created by 肖浩然的mac on 2018/2/6.
//  Copyright © 2018年 RUIXIN. All rights reserved.
//

#import "FCRegisteVC.h"
#import "FCLoginVC.h"
@interface FCRegisteVC ()<UITextFieldDelegate>

/* emailField */
@property (strong, nonatomic) UITextField *emailField;
/* passwordField */
@property (strong, nonatomic) UITextField *passwordField;
/* confirmField */
@property (strong, nonatomic) UITextField *confirmField;
//协议按钮
@property (strong, nonatomic) UIButton *protocolBtn;
/* registerBtn */
@property (strong, nonatomic) UIButton *registerBtn;
@end

@implementation FCRegisteVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.showBackItem = YES;
    //监听键盘
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [self setupUI];
    [FCLocalUserHelper saveIsMainVC:@"0"];
    
    
}

#pragma mark-设置UI
-(void)setupUI{
    //背景图片
    UIImageView *bgImageView = [UIImageView new];
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    bgImageView.image = [UIImage imageNamed:@"bg_login"];
    //注册label
    UILabel *signLabel = [UILabel new];
    [self.view addSubview:signLabel];
    [signLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            if (iPhoneX) {
                make.left.mas_equalTo(32*KScreenWidthScale750);
                make.top.mas_equalTo((100)*KScreenHeightScale1334);
                
            }else{
                make.left.mas_equalTo(32*KScreenWidthScale750);
                make.top.mas_equalTo(100*KScreenHeightScale1334);
                
            }
        }else{
            make.left.mas_equalTo(32*KScreenWidthScale750);
            make.top.mas_equalTo(100*KScreenHeightScale1334);
            
        }
    }];
    signLabel.text = Localized(@"注册");
    signLabel.font = KOverstrikingfont(52);
    //提示语
    UILabel *hintLabel = [UILabel new];
    [self.view addSubview:hintLabel];
    [hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(signLabel);
        make.top.mas_equalTo(signLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        
    }];
    hintLabel.font = Kfont(28);
    hintLabel.textColor = kGrayColor;
    hintLabel.text = Localized(@"还没有钱包？请免费创建一个钱包。");
    //邮箱标题
    UILabel *emailLabel = [UILabel new];
    [self.view addSubview:emailLabel];
    [emailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(signLabel);
        make.top.mas_equalTo(hintLabel.mas_bottom).offset(120*KScreenHeightScale1334);
        
    }];
    emailLabel.font = Kfont(32);
    emailLabel.textColor = kGrayColor;
    emailLabel.text = Localized(@"邮箱");
    //输入邮箱
    UITextField *emailField = [UITextField new];
    self.emailField = emailField;
    [self.view addSubview:emailField];
    [emailField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(emailLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.left.mas_equalTo(signLabel);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
    }];
    emailField.keyboardType = UIKeyboardTypeEmailAddress;
    //分割线
    UIView *viewLine1 =[UIView new];
    [self.view addSubview:viewLine1];
    [viewLine1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(emailField);
        make.top.mas_equalTo(emailField.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    viewLine1.backgroundColor =kLineColor;
    //密码标题
    UILabel *passwordLabel = [UILabel new];
    [self.view addSubview:passwordLabel];
    [passwordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(signLabel);
        make.top.mas_equalTo(viewLine1.mas_bottom).offset(80*KScreenHeightScale1334);
        
    }];
    passwordLabel.font = Kfont(32);
    passwordLabel.textColor = kGrayColor;
    passwordLabel.text = Localized(@"密码");
    //输入密码
    UITextField *passwordField = [UITextField new];
    self.passwordField = passwordField;
    [self.view addSubview:passwordField];
    [passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(passwordLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.left.mas_equalTo(signLabel);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
    }];
    passwordField.secureTextEntry = YES;
    passwordField.delegate = self;
    [passwordField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    //分割线
    UIView *viewLine2 =[UIView new];
    [self.view addSubview:viewLine2];
    [viewLine2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(passwordField);
        make.top.mas_equalTo(passwordField.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    viewLine2.backgroundColor =kLineColor;
    //确定密码标题
    UILabel *confirmLabel = [UILabel new];
    [self.view addSubview:confirmLabel];
    [confirmLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(signLabel);
        make.top.mas_equalTo(viewLine2.mas_bottom).offset(80*KScreenHeightScale1334);
        
    }];
    confirmLabel.font = Kfont(32);
    confirmLabel.textColor = kGrayColor;
    confirmLabel.text = Localized(@"确认密码");
    //确定输入密码
    UITextField *confirmField = [UITextField new];
    self.confirmField = confirmField;
    [self.view addSubview:confirmField];
    [confirmField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(confirmLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.left.mas_equalTo(signLabel);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
    }];
    confirmField.secureTextEntry = YES;
    confirmField.delegate = self;
    [confirmField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    //分割线
    UIView *viewLine3 =[UIView new];
    [self.view addSubview:viewLine3];
    [viewLine3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(confirmField);
        make.top.mas_equalTo(confirmField.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    viewLine3.backgroundColor =kLineColor;
    
    //注册按钮
    UIButton *registerBtn = [UIButton new];
    self.registerBtn = registerBtn;
    [self.view addSubview:registerBtn];
    [registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30*KScreenWidthScale750);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
        make.bottom.mas_equalTo(-100*KScreenHeightScale1334);
        make.height.mas_equalTo(112*KScreenHeightScale1334);
    }];
    if (SCREEN_WIDTH == 320) {
        [registerBtn mas_updateConstraints:^(MASConstraintMaker *make) {
           make.bottom.mas_equalTo(-40*KScreenHeightScale1334);
        }];
    }
    registerBtn.layer.cornerRadius = 5.0;
    registerBtn.layer.masksToBounds = YES;
    registerBtn.titleLabel.font = KOverstrikingfont(36);
    [registerBtn setTitle:Localized(@"创建钱包") forState:(UIControlStateNormal)];
    [registerBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [registerBtn setBackgroundColor:kLightblueColor];
    //协议按钮
    UIButton *protocolBtn = [UIButton new];
    self.protocolBtn = protocolBtn;
    [self.view addSubview:protocolBtn];
    [protocolBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(registerBtn);
        make.bottom.mas_equalTo(registerBtn.mas_top).offset(-70*KScreenHeightScale1334);
        make.size.mas_equalTo(CGSizeMake(16, 16));
    }];
    [protocolBtn setImage:[UIImage imageNamed:@"check_n"] forState:(UIControlStateNormal)];
    [protocolBtn setImage:[UIImage imageNamed:@"check_s"] forState:(UIControlStateSelected)];
    //协议label
    UILabel *protocolLabel = [UILabel new];
    [self.view addSubview:protocolLabel];
    [protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(protocolBtn.mas_right).offset(16*KScreenWidthScale750);
        make.right.mas_equalTo(-50*KScreenWidthScale750);
        make.height.mas_equalTo(80*KScreenHeightScale1334);
        make.top.mas_equalTo(protocolBtn).offset(-10);
    }];
    protocolLabel.numberOfLines = 2;
    protocolLabel.font = Kfont(24);
    protocolLabel.text = Localized(@"我已阅读条款和条件，并同意隐私政策。");
    protocolLabel.textColor = kGrayColor;
    
    //事件
    [protocolBtn addTarget:self action:@selector(protocolBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [registerBtn addTarget:self action:@selector(registerBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
}

#pragma mark-注册

-(void)registerBtnClick:(UIButton*)sender{
    
    if (self.emailField.text.trimWhitespace.length <= 0 || self.passwordField.text.trimWhitespace.length <= 0 || self.confirmField.text.trimWhitespace.length <= 0) {
        return;
        
    }
    if (self.protocolBtn.selected) {
    }else{
        [self showAlert:Localized(@"请先同意隐私政策")];
        return;
    }
    if (self.passwordField.text.trimWhitespace.length <6 || self.passwordField.text.trimWhitespace.length >16) {
        [self hideProgress];
        [self showAlert:Localized(@"密码必须为6-16位字符，区分大小写")];
        return;
    }else if (![self.passwordField.text.trimWhitespace isEqualToString: self.confirmField.text.trimWhitespace]){
       
        [self showAlert:Localized(@"密码和确认密码不一致")];
        
        return;
    }else if (![FCLocalUserHelper isValidateEmail:self.emailField.text.trimWhitespace]){
        
        [self showAlert:Localized(@"电子邮件地址不存在，请重新输入。")];
        return;
    }
    [self showChrysanthemumAlert:nil];
    NSString *url = [NSString stringWithFormat:@"%@",Register_URL];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setObject:self.emailField.text.trimWhitespace forKey:@"email"];
    [dic setObject:self.passwordField.text.trimWhitespace forKey:@"passWord"];
    
    [FCSharedNetworkTool POSTWithURLString:url parameters:dic success:^(id responseObject) {
        NSLog(@"res:%@",responseObject);
        NSDictionary *dict = responseObject;
        NSNumber *str = dict[@"code"];
        NSNumber *two = [[NSNumber alloc]initWithLong:200];
        NSNumber *free = [[NSNumber alloc]initWithLong:402];
        if (str == two) {
            NSLog(@"注册成功");
            [self hideProgress];
            [FCLocalUserHelper cleanLoginState];
            [self showAlert:Localized(@"注册成功")];
            //保存注册邮箱
//            [FCLocalUserHelper saveUserEmailStr:self.emailField.text];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self getLoginVC:self.emailField.text.trimWhitespace:self.passwordField.text.trimWhitespace];
            });
            
            
        }else if (str == free){
            [self hideProgress];
            [self showAlert:Localized(@"邮箱已经被注册")];
        }else if ([responseObject[@"code"] integerValue] == 404){
            [self hideProgress];
            [self showAlert:Localized(@"注册失败")];
        }else if ([responseObject[@"code"] integerValue] == 407){
            
            [self hideProgress];
            [self showAlert:Localized(@"电子邮件地址不存在，请重新输入。")];
        }
    } faile:^(NSError *error) {
        
        NSLog(@"error:%@",error);
    }];
    
    
}
#pragma mark-跳转登陆界面
-(void)getLoginVC:(NSString*)accountStr:(NSString*)passWordStr{
    
    FCLoginVC *vc = [FCLoginVC new];
    vc.accountStr = accountStr;
    vc.passWordStr = passWordStr;
    [self.navigationController pushViewController:vc animated:NO];
}
#pragma mark-同意协议
-(void)protocolBtnClick:(UIButton*)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        
        [self.registerBtn setBackgroundColor:kRedOrangeColor];;
    }else{
        [self.registerBtn setBackgroundColor:kLightblueColor];
    }
    
}
-(void)textFieldDidChange:(UITextField *)textField{
    
    if(self.passwordField == textField||textField == self.confirmField ){
        if (textField.text.trimWhitespace.length > 16) {
            textField.text = [textField.text substringToIndex:16];
            
        }
    }
}
////#pragma mark - 键盘弹出时界面上移及还原
//-(void)keyBoardWillShow:(NSNotification *) notification{
//
//    //获取键盘的高度
//    NSDictionary *userInfo = [notification userInfo];
//    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [aValue CGRectValue];
//    int keyBoardHeight = keyboardRect.size.height;
//
//    //使视图上移
//    CGRect viewFrame = self.view.frame;
//
//    viewFrame.origin.y = -keyBoardHeight/2;//上移1/2的键盘高度
//    self.view.frame = viewFrame;
//
//}
//
//- (void)keyBoardWillHide:(NSNotification *) notification {
//    //当键盘消失时执行方法使视图下滑回原位
//    NSTimeInterval time = [[notification.userInfo objectForKey:@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
//    [UIView animateWithDuration:time animations:^{
//        CGRect frame = self.view.frame;
//        frame.origin.y = 64;
//        self.view.frame = frame;
//        [self.view layoutIfNeeded];
//    }];
//}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //移除第一响应
    [self.emailField resignFirstResponder];
    [self.passwordField resignFirstResponder];
    [self.confirmField resignFirstResponder];
}
@end

